<template>
  <a-modal :title="title" :visible="visible" width="85vw" unmount-on-close @cancel="close">
    <div class="CarSelector-body">
      <!-- 车辆来源 -->
      <div v-if="mode == 'paltoon'">
        <a-alert type="info" class="mb-2" v-if="orderInfo?.channelOrderMaintenance == 1">
          <div> 在启程进行【修改车牌号】的操作，后续将不再以渠道平台订单的车辆进行更新。 </div>
        </a-alert>
        <div class="page-form-block">
          <!-- 统计 -->
          <summary-info :summaryList="summaryLease" />
        </div>
        <a-divider />
        <a-form layout="vertical" style="overflow-x: hidden" :model="stockState.queryParam">
          <a-form-item label="车辆来源" required class="mb-0">
            <a-radio-group v-model="stockState.queryParam.carSource" @change="carSourceChange">
              <a-radio :value="1">门店车辆</a-radio>
              <a-radio :disabled="canOtherSite == false" :value="3">跨门店调车</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
        <a-divider />
      </div>

      <list-searcher
        v-if="stockState.queryParamLoaded"
        :searchList="searchList"
        v-model:searchForm="stockState.queryParam"
        @loadData="loadData"
      />
      <!-- 标签 -->
      <TagList :data="stockState.statistics" :selectable="false" />
      <!-- 骨架屏 -->
      <a-skeleton v-if="initLoading" :animation="true">
        <a-skeleton-line :rows="5" :line-height="90" />
      </a-skeleton>
      <!-- 排车table -->
      <StockTable v-else />
    </div>

    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" @click="onSubmit" :loading="okLoading">确认</a-button>
    </template>

    <!-- 二次确认 -->
    <a-modal title="提示" v-model:visible="confirmVisible">
      <div v-for="(it, i) in resultMsg" :key="i">{{ it }}</div>
      <div>请确认是否{{ props.title == '修改车牌号' ? '修改车牌号' : '排车' }}？</div>
      <template #footer>
        <a-button @click="confirmVisible = false">关闭</a-button>
        <a-button type="primary" @click="confirmSubmit" :loading="okLoading">确认</a-button>
      </template>
    </a-modal>
  </a-modal>
</template>

<script lang="ts" setup name="CarSelector">
  import dayjs from 'dayjs'
  import { ref, computed, provide, reactive, nextTick } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import StockTable from './car/components/table/index.vue'
  import TagList from './components/tag-list.vue'
  import { getDayList, ininStockData } from './car/components/table/tableUtil'
  import summaryInfo from '@/views/order/short-order/components/summary-info.vue'
  import { Notification } from '@arco-design/web-vue'
  import { getCarSotckData, platoonCarCheck, platoonCar } from '@/api/asset/carStock'
  import { searchForStaff } from '@/api/asset/car'
  import { longPlatoonCar, updateLongCarLicenseNo } from '@/api/order/czsOrder'
  import { updateCarLicenseNo } from '@/api/order/sOrder'
  import { getSysCarModelDetail } from '@/api/asset/carModel'
  import { orderIsTiexing } from '@/views/order/short-order/utils.js'

  // 订单拦截hooks
  import useOrderIntercept from '@/views/order/short-order/hooks/useTieXingInterceptor'
  import { usePageDict } from '@/hooks/useDict'

  const dict = usePageDict('carStockDict')
  const props = defineProps({
    title: {
      type: String,
      default: '选择车辆',
    },
    scrollbar: Boolean,
    // 排车还是选择车辆
    mode: {
      type: String,
      default: 'paltoon', // paltoon | select
    },
    isLongOrder: {
      type: Boolean,
      default: false,
    },
  })

  // 查询条件；
  // list-searcher 做了v-if 保证了重置的数据正确
  // list-searcher 回显门店、车型、时间；车系、车牌号不回显
  const searchList = computed(() => {
    const queryParam = stockState.queryParam
    return [
      {
        label: '门店',
        prop: 'siteId',
        type: 'remote-select',
        attrs: {
          allowClear: false,
          popupContainer: '.CarSelector-body .remote-select-wrapper',
          //  本门店车辆部允许修改门店
          disabledValue: stockState.queryParam.carSource == 1 ? undefined : disabledSite,
          disabled: stockState.queryParam.carSource == 1,
          // mountedLoad: false,
          params: { oldId: stockState.queryParam.siteId, siteStatusList: [10] },
          type: 'site_listBystaff',
          change: () => {
            stockState.queryParam.seriesIdList = undefined
            stockState.queryParam.modelIdList = []
          },
        },
      },
      {
        label: '车系',
        prop: 'seriesIdList',
        type: 'remote-select',
        attrs: {
          // mountedLoad: false,
          type: 'multiple_carSeries_bySite',
          popupContainer: '.CarSelector-body .remote-select-wrapper',
          params: {
            siteId: queryParam.siteId,
          },
          change: () => {
            stockState.queryParam.modelIdList = []
            stockState.queryParam.carIdList = []
          },
        },
      },
      {
        label: '车型',
        prop: 'modelIdList',
        type: 'remote-select',
        attrs: {
          // mountedLoad: false,
          type: 'multiple_car_model_bySite',
          popupContainer: '.CarSelector-body .remote-select-wrapper',
          params: {
            siteId: queryParam.siteId,
            seriesIdList: queryParam.seriesIdList,
          },
          fallbackOption: currentModel,
          change: () => {
            stockState.queryParam.carIdList = []
          },
        },
      },
      {
        label: '车牌号',
        prop: 'carIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_carLicensenno_bySite',
          popupContainer: '.CarSelector-body .remote-select-wrapper',
          params: {
            siteId: stockState.queryParam.siteId,
            seriesIdList: queryParam.seriesIdList,
            modelIdList: queryParam.modelIdList,
          },
        },
      },
      {
        label: '时间',
        prop: 'dateRange',
        type: 'i-range-picker',
        disabled: true,
      },
      {
        label: '订单渠道',
        prop: 'channelTypeList',
        type: 'a-select',
        options: dict.channelTypeEnum,
        attrs: { multiple: true },
      },
    ]
  })

  // 局部状态管理
  const stockState = reactive({
    dayList: [] as any,
    dayPx: 0,
    hourPx: 0,
    stockData: [],
    statistics: {},
    // 接口参数（不包含page信息）
    queryParam: {
      siteId: undefined,
      seriesIdList: undefined,
      modelIdList: [],
      carIdList: [],
      channelTypeList: [],
      carSource: 1,
      type: undefined,
      dateRange: [],
      startTime: '',
      endTime: '',
    },
    queryParamLoaded: false,
    // 选择器
    selector: {
      id: undefined,
      c_id: undefined, // 当前车辆
      info: undefined,
    },
    // 滚动位置
    scrollTop: 0,
  })
  provide('stockState', stockState)

  // 关闭
  const visible = ref(false)
  // 排车类型:1排车 2改排
  let platoonType = 1
  const close = () => {
    visible.value = false
    stockState.scrollTop = 0
    platoonType = 1
  }

  // 弹框open
  const orderInfo = ref({} as any) // 订单信息
  const summaryLease = ref([] as any)
  const open = (data: any, info: any) => {
    stockState.queryParamLoaded = false
    // platoonType 排车类型 api提供参数
    if (info.platoonCarId) {
      platoonType = 2
    }
    // 初始化选中车辆
    stockState.selector = {
      id: data.id,
      c_id: info.platoonCarId, // 排车的车辆id
      info: undefined,
    }

    // 初始化请求参数
    stockState.queryParam.seriesIdList = undefined
    stockState.queryParam.channelTypeList = []

    // 更换车牌号且不为跨门店调车时，不回显车型
    if (data.isEditLicenseNo && data.carSource == 1) {
      stockState.queryParam.modelIdList = []
    } else {
      stockState.queryParam.modelIdList = data.modelId ? [data.modelId + ''] : []
    }

    stockState.queryParam.dateRange = data.dateRange
    // 车辆来源 本门店or其他门店
    stockState.queryParam.carSource = data.carSource

    // 初始化加载列表数据
    initLoadData(data, info)
    visible.value = true

    // 记录订单信息
    orderInfo.value = info
    console.log(orderInfo.value, 'orderInfo.value')

    // 初始化统计信息
    if (props.mode == 'paltoon') {
      const summaryList = [
        [
          {
            label: '预计租赁周期',
            value: `${info.startTime} 至 ${info.endTime}`,
          },
          { label: '租期', value: info.rentDays },
          { label: '订单来源', value: info.orderSourceName },
        ],
        [
          { label: '订单获取方式', value: info.orderAcquisitionTypeName },
          { label: '车型', value: info.carModelName },
        ],
      ]
      // 线上订单显示渠道车型
      if (info.orderSource == 2) {
        summaryList[1].push({
          label: '渠道车型',
          value: info.channelModelName,
        })
      }
      summaryLease.value = summaryList
    }
  }
  defineExpose({
    open,
  })

  // 确认
  const emits = defineEmits(['confirm', 'ok'])
  const onSubmit = () => {
    if (!stockState.selector.id) {
      Message.warning('请选择车辆')
      return
    }
    if (props.mode == 'paltoon' && (orderInfo.value.orderStatus == 300 || orderInfo.value.status == 300)) {
      confirmSubmit()
    } else {
      platoonCarVerify(() => {
        confirmSubmit()
      })
    }
  }

  // 询问确认
  const cacheQueryParam = ref({})
  const confirmSubmit = () => {
    if (props.mode == 'paltoon') {
      platoonCarFn()
    } else {
      emits('confirm', stockState.selector.id, stockState.selector.info, {
        // 记录门店id、车系、车型
        siteId: cacheQueryParam.value.siteId,
        seriesIdList: cacheQueryParam.value.seriesIdList,
        modelIdList: cacheQueryParam.value.modelIdList,
      })
      confirmVisible.value = false
      close()
    }
  }

  // 排车校验
  const resultMsg = ref([])
  const confirmVisible = ref(false)
  const platoonCarVerify = (callback: any) => {
    // 长短租判断
    let useType = 2
    if (props.isLongOrder) {
      useType = 3
    }
    const params = {
      refId: orderInfo.value.id,
      startTime: orderInfo.value.startTime,
      endTime: orderInfo.value.endTime,
      useType,
      carId: stockState.selector.id,
      modelId: orderInfo.value.modelId,
    }
    platoonCarCheck(params).then((res) => {
      const msgList = res.result.resultMsg || []
      if (msgList.length) {
        resultMsg.value = msgList
        confirmVisible.value = true
        return
      }
      callback && callback()
    })
  }
  // 排车
  const okLoading = ref(false)
  const platoonCarFn = () => {
    if (props.title == '修改车牌号') {
      // 已还车/已完成的订单，修改车牌号不调用铁行接口，弹窗拦截进行提示
      if (orderIsTiexing(orderInfo.value) && [300, 1000].includes(orderInfo.value.orderStatus)) {
        return useOrderIntercept(orderInfo.value, 'notCallTiexing', () => {
          updateCarLicenseNoFn()
        })
      }
      updateCarLicenseNoFn()
    } else {
      platoonCarOperateFn()
    }
  }
  // 排车/改排操作
  const platoonCarOperateFn = () => {
    const params = {
      id: orderInfo.value.id,
      carId: stockState.selector.id,
      carSource: stockState.queryParam.carSource, // 修改后的订单来源，跟新订单信息
      type: platoonType,
    }
    okLoading.value = true
    let fetch = props.isLongOrder ? longPlatoonCar : platoonCar
    fetch(params)
      .then(({ result }) => {
        confirmVisible.value = false
        // 待用车的订单 调用铁行的接口 false = 失败，弹出警告弹窗 platoonType = 2 改排
        if (platoonType == 2 && orderInfo.value.orderStatus == 100 && result && result.success == false) {
          let { info } = stockState.selector
          return useOrderIntercept({ ...orderInfo.value, carLicenseNo: info?.licenseNo }, 'editShortOrderReschedule', () => {
            emits('ok')
            close()
          })
        }
        Notification.success({
          content: '保存成功',
          closable: true,
          duration: 3000,
        })
        emits('ok')
        close()
      })
      .finally(() => {
        okLoading.value = false
      })
  }
  // 修改车牌号操作
  const updateCarLicenseNoFn = () => {
    const params = {
      orderId: orderInfo.value.id,
      carId: stockState.selector.id,
      carSource: stockState.queryParam.carSource,
      oldOrderCarId: orderInfo.value.oldOrderCarId, //用车记录ID
    }
    okLoading.value = true
    let fetch = props.isLongOrder ? updateLongCarLicenseNo : updateCarLicenseNo
    fetch(params)
      .then((res: any) => {
        // 短租 待用车、用车中的订单，修改车牌号 调用铁行接口 false = 失败
        if (!props.isLongOrder && [100, 200].includes(orderInfo.value.orderStatus) && res.result.success == false) {
          let { info } = stockState.selector
          return useOrderIntercept({ ...orderInfo.value, carLicenseNo: info?.licenseNo }, 'editShortOrderLicenseNo', () => {
            confirmVisible.value = false
            emits('ok')
            close()
          })
        }
        console.log(res, 'res')
        confirmVisible.value = false
        Message.success(res.result?.msg || res.message || '操作成功')
        emits('ok')
        close()
      })
      .finally(() => {
        okLoading.value = false
      })
    console.log(orderInfo.value, 'orderInfo.value')
  }
  // 加载数据
  const initLoading = ref(false)
  const listLoading = ref(false)
  // 最小1天，最大100天
  const calcParamEndtime = (startTime: string, endTime: string) => {
    const start = dayjs(startTime).startOf('day')
    // 处理为开始为当天的0点、结束时间为当天的23:59:59
    stockState.queryParam.startTime = start.format('YYYY-MM-DD 00:00:00')
    stockState.queryParam.endTime = dayjs(endTime).format('YYYY-MM-DD 23:59:59')
    const min = start.add(14, 'day').subtract(1, 'second')
    const max = start.add(100, 'day').subtract(1, 'second')
    if (min.isAfter(endTime)) {
      stockState.queryParam.endTime = min.format('YYYY-MM-DD HH:mm:ss')
    }
    if (max.isBefore(endTime)) {
      stockState.queryParam.endTime = max.format('YYYY-MM-DD HH:mm:ss')
    }
  }
  // 车辆来源参数处理; 跨门店调车 门店充值为其他门店初始值
  const calcParamCarSource = () => {
    const query = stockState.queryParam
    if (query.carSource == 3) {
      if (query.siteId == initSiteId.value) {
        query.siteId = initOtherSiteId.value
        query.modelIdList = []
      }
    }
  }
  const loadData = () => {
    listLoading.value = true
    const query = stockState.queryParam
    calcParamEndtime(query.dateRange[0], query.dateRange[1])
    calcParamCarSource()
    cacheQueryParam.value = { ...query }

    // 清空库存数据
    initLoading.value = true
    getCarSotckData(query).then((res) => {
      initLoading.value = false
      listLoading.value = false

      const { dayList, hourPx, dayPx } = getDayList(query.startTime, query.endTime)
      stockState.dayList = dayList
      stockState.dayPx = dayPx
      stockState.hourPx = hourPx
      stockState.stockData = ininStockData(res.result.list)
      stockState.statistics = res.result.statistics
      // 打开弹框不选择数据时回显上次选中的信息
      let stockData = res.result.list
      let selectorId = stockState.selector.id
      const allData = ref([])
      stockData.forEach((item) => {
        if (item.carList) {
          allData.value.push(...item.carList)
        }
      })
      let selectInfo = allData.value.find((i) => i.carId == selectorId)
      stockState.selector.info = selectInfo
      // 重置滚动位置
      stockState.scrollTop = 0
    })
  }
  provide('loadDataFn', loadData)

  // 初始化加载数据
  let disabledSite = ''
  const initSiteId = ref()
  const initOtherSiteId = ref()
  const canOtherSite = ref(true)
  let currentModel = {}
  const initLoadData = (data: any, info: any) => {
    disabledSite = ''
    // 跨门店禁止选择本门店
    disabledSite = info.siteId
    // 记录初始化门店id
    initSiteId.value = info.siteId
    if (data.carSource != 3) {
      stockState.queryParam.siteId = info.siteId
      loadData()
    }
    // 初始化跨门店id
    searchForStaff({ siteStatusList: [10] }).then((res: any) => {
      if (res.code == 200) {
        const other_site = res.result.find((it: any) => it.id != info.siteId)
        if (other_site) {
          initOtherSiteId.value = other_site.id
          // 选择门店并获取数据；跨门店使用其他门店id
          if (data.carSource == 3) {
            // 缓存了，取上次查询门店，并不清空车型
            if (data.siteId) {
              stockState.queryParam.siteId = data.siteId
            } else {
              // stockState.queryParam.modelIdList = []
              stockState.queryParam.siteId = other_site.id
              // 2024-07-09，跨门店清空车型（新门店可能没此车型）改为回显
              // 增加没值的回显option
              if (data.modelId) {
                nextTick(() => {
                  stockState.queryParamLoaded = false
                  getSysCarModelDetail({ id: data.modelId }).then((res: any) => {
                    const modelName = res.result.modelName
                    currentModel = {
                      value: data.modelId + '',
                      label: modelName,
                    }
                    stockState.queryParamLoaded = true
                  })
                })
              }
            }
            loadData()
          }
        } else {
          canOtherSite.value = false
          if (data.carSource == 3) {
            Notification.warning({
              title: '提示',
              content: '无法跨门店选择车辆，没有其他门店',
              closable: true,
              duration: 3000,
            })
            close()
          }
        }
        // list-searcher的参数已完成加载
        stockState.queryParamLoaded = true
      }
    })
  }
  // 车辆来源change,重置为初始门店
  const carSourceChange = (val: number) => {
    // 清空当前车系、车型、选择的车辆
    stockState.queryParam.seriesIdList = undefined
    stockState.queryParam.modelIdList = []
    stockState.queryParam.carIdList = []
    stockState.selector.id = undefined
    if (val == 1) {
      stockState.queryParam.siteId = initSiteId.value
    } else {
      stockState.queryParam.siteId = initOtherSiteId.value
    }
    loadData()
  }
</script>

<style lang="less" scoped>
  .CarSelector-body {
    height: 80vh;
  }
  .order-block {
    background: rgba(247, 248, 250, 0.5);
    padding: 20px 0;
  }
  :deep(.arco-descriptions-item-label-inline) {
    width: 120px;
    display: inline-block;
  }
</style>
